//
//  DNTabbarViewController.swift
//  LunalerApp
//
//  Created by 露乐ios on 2018/2/6.
//  Copyright © 2018年 露乐ios. All rights reserved.
//

import UIKit
import ESTabBarController_swift

@objc protocol DNMainTabBarVCDelegate : NSObjectProtocol {
    
    @objc optional func tabBarControllerDidSelectindex(tabBarController:DNTabbarViewController,index:NSInteger) -> Void
}




class DNTabbarViewController: ESTabBarController {
    
    var mainTabDelegate : DNMainTabBarVCDelegate?
    
    static let shareInstance = DNTabbarViewController()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.resetTabBarVC()
        
        let v1 = ViewController()
        let v2 = ViewController()
        let v3 = ViewController()
        let v4 = ViewController()
        let v5 = DNMineVC()
        
        v1.tabBarItem = ESTabBarItem.init(title: "首页", image: UIImage(named: "tab_btn_home"), selectedImage: UIImage(named: "tab_btn_home_hl"))
        v2.tabBarItem = ESTabBarItem.init(title: "统计", image: UIImage(named: "tab_btn_statistics"), selectedImage: UIImage(named: "tab_btn_statistics_hl"))
//        v3.tabBarItem = ESTabBarItem.init(title: "", image: UIImage(named: "tab_btn_PK"), selectedImage: UIImage(named: "tab_btn_PK"))
        
        v3.tabBarItem = ESTabBarItem.init(title: "", image: UIImage(named: "photo_big"), selectedImage: UIImage(named: "photo_big"))
        
        v4.tabBarItem = ESTabBarItem.init(title: "排行榜", image: UIImage(named: "tab_btn_race"), selectedImage: UIImage(named: "tab_btn_race_hl"))
        v5.tabBarItem = ESTabBarItem.init(title: "我的", image: UIImage(named: "tab_btn_user"), selectedImage: UIImage(named: "tab_btn_user_hl"))
        
        let n1 = DNBaseNavigationController.init(rootViewController: v1)
        let n2 = DNBaseNavigationController.init(rootViewController: v2)
        let n3 = DNBaseNavigationController.init(rootViewController: v3)
        let n4 = DNBaseNavigationController.init(rootViewController: v4)
        let n5 = DNBaseNavigationController.init(rootViewController: v5)
        
        
        v1.title = "首页"
        v2.title = "统计"
        v3.title = ""
        v4.title = "排行榜"
        v5.title = "我的"
        
        self.viewControllers = [n1, n2, n3, n4, n5]
        
        
    }
    
    func resetTabBarVC(){
        self.delegate = self
        self.tabBar.backgroundColor = UIColor.white
        self.tabBar.isTranslucent = false
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
}


class ExampleIrregularityContentView: ESTabBarItemContentView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.imageView.backgroundColor = UIColor.red
        self.imageView.layer.borderWidth = 3.0
        self.imageView.layer.borderColor = UIColor.init(white: 235 / 255.0, alpha: 1.0).cgColor
        self.imageView.layer.cornerRadius = 0
        self.insets = UIEdgeInsetsMake(5, 0, -5, 0)
        let transform = CGAffineTransform.identity
        self.imageView.transform = transform
        self.superview?.bringSubview(toFront: self)
        
        textColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0)
        highlightTextColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0)
        iconColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0)
        highlightIconColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0)
        backdropColor = .clear
        highlightBackdropColor = .clear
    }
    
    public required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        let p = CGPoint.init(x: point.x - imageView.frame.origin.x, y: point.y - imageView.frame.origin.y)
        return sqrt(pow(imageView.bounds.size.width / 2.0 - p.x, 2) + pow(imageView.bounds.size.height / 2.0 - p.y, 2)) < imageView.bounds.size.width / 2.0
    }
    
    override func updateLayout() {
        super.updateLayout()
        self.imageView.sizeToFit()
        self.imageView.center = CGPoint.init(x: self.bounds.size.width / 2.0, y: self.bounds.size.height / 2.0)
    }
    
    public override func selectAnimation(animated: Bool, completion: (() -> ())?) {
        let view = UIView.init(frame: CGRect.init(origin: CGPoint.zero, size: CGSize(width: 2.0, height: 2.0)))
        view.layer.cornerRadius = 1.0
        view.layer.opacity = 0.5
        view.backgroundColor = UIColor.init(red: 10/255.0, green: 66/255.0, blue: 91/255.0, alpha: 1.0)
        self.addSubview(view)
        playMaskAnimation(animateView: view, target: self.imageView, completion: {
            [weak view] in
            view?.removeFromSuperview()
            completion?()
        })
    }
    
    public override func reselectAnimation(animated: Bool, completion: (() -> ())?) {
        completion?()
    }
    
    public override func deselectAnimation(animated: Bool, completion: (() -> ())?) {
        completion?()
    }
    
    public override func highlightAnimation(animated: Bool, completion: (() -> ())?) {
        UIView.beginAnimations("small", context: nil)
        UIView.setAnimationDuration(0.2)
        let transform = self.imageView.transform.scaledBy(x: 0.8, y: 0.8)
        self.imageView.transform = transform
        UIView.commitAnimations()
        completion?()
    }
    
    public override func dehighlightAnimation(animated: Bool, completion: (() -> ())?) {
        UIView.beginAnimations("big", context: nil)
        UIView.setAnimationDuration(0.2)
        let transform = CGAffineTransform.identity
        self.imageView.transform = transform
        UIView.commitAnimations()
        completion?()
    }
    
    private func playMaskAnimation(animateView view: UIView, target: UIView, completion: (() -> ())?) {
        
        view.center = CGPoint.init(x: target.frame.origin.x + target.frame.size.width / 2.0, y: target.frame.origin.y + target.frame.size.height / 2.0)
        completion?()
//        let scale = POPBasicAnimation.init(propertyNamed: kPOPLayerScaleXY)
//        scale?.fromValue = NSValue.init(cgSize: CGSize.init(width: 1.0, height: 1.0))
//        scale?.toValue = NSValue.init(cgSize: CGSize.init(width: 36.0, height: 36.0))
//        scale?.beginTime = CACurrentMediaTime()
//        scale?.duration = 0.3
//        scale?.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseOut)
//        scale?.removedOnCompletion = true
        
//        let alpha = POPBasicAnimation.init(propertyNamed: kPOPLayerOpacity)
//        alpha?.fromValue = 0.6
//        alpha?.toValue = 0.6
//        alpha?.beginTime = CACurrentMediaTime()
//        alpha?.duration = 0.25
//        alpha?.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseOut)
//        alpha?.removedOnCompletion = true
//
//        view.layer.pop_add(scale, forKey: "scale")
//        view.layer.pop_add(alpha, forKey: "alpha")
        
//        scale?.completionBlock = ({ animation, finished in
//            completion?()
//        })
    }
    
}

typealias LoginSuccessBlock = ()->Void

typealias ShowLoginVCStyleBlock = (UIViewController)->Void

extension DNTabbarViewController {
    
    
    func backToUserSetIndex(index:NSInteger) -> Void {
        backToUserSetIndex(index: index, isShowLoginVC: false, loginSuccessBlock: nil, showLoginVCStyle: nil)
    }
    
    
    func backToUserSetIndex(index:NSInteger, isShowLoginVC:Bool,loginSuccessBlock:LoginSuccessBlock?,showLoginVCStyle:ShowLoginVCStyleBlock?) -> Void {
        
        if self.childViewControllers.count < index {
            return
        }
        
        // 返回TabBar层
        let navi = self.selectedViewController as! UINavigationController
        let vc = self.presentedViewController
        if (vc != nil) {
            vc?.dismiss(animated: false, completion: nil)
        }
        
        if isShowLoginVC {
            let vc = DNLoginVC.defaultViewController()
            if isShowLoginVC{
                if showLoginVCStyle != nil {
                   showLoginVCStyle!(vc)
                }
            }
        let nav = DNBaseNavigationController.init(rootViewController: vc)
        self.present(nav, animated: true, completion: nil)
        }else{
            self.selectedIndex = index
        }
        navi.popToRootViewController(animated: false)
        self.view.setNeedsLayout()
    }
    
}

extension DNTabbarViewController : UITabBarControllerDelegate{
    
    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        if self.mainTabDelegate != nil && (self.mainTabDelegate?.responds(to: #selector(DNMainTabBarVCDelegate.tabBarControllerDidSelectindex(tabBarController:index:))))! {
            self.mainTabDelegate?.tabBarControllerDidSelectindex!(tabBarController: self, index: self.selectedIndex)
        }
    }
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        if viewController.isKind(of: UINavigationController.self) {
            
            let nav = viewController as! UINavigationController
            nav.popToRootViewController(animated: false)
            
            if nav.viewControllers.count > 0 && (nav.viewControllers.first?.isKind(of: DNMineVC.self))!{
                if checkLogin() {
                    return true
                }else{
                    return false
                }
            }
        }
        return true
    }
    
    
    func checkLogin() -> Bool {
        if DNUserContext.sharedInstance.isLogin == false {
            let vc = DNLoginVC.defaultViewController()
            let navi = DNBaseNavigationController.init(rootViewController: vc)
            self.present(navi, animated: true, completion: nil)
            return false
        }else{
            return true
        }
    }
    
}
